package com.gljx.web.controller;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.service.CarService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.GoodstableService;
import com.gljx.web.service.InwareHouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by rhc on 2018/5/22 0022.
 */
@Controller
@RequestMapping("/")
public class InwareHouseController {

    @Autowired
    private InwareHouseService inwarehouseService;
    //自动注入
    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private GoodstableService goodstableService;
    //自定义流程工具
    private Axamine axamine = new Axamine();

    /**
     * 主页面
     * @param request
     * @return
     */
    @RequestMapping("/queryswareHouse/look.action")
    public String showSwareHouse(HttpServletRequest request,String type){

       //获取
        PageBean<InwareHouse> pb = new PageBean<>();
        //获取操作人信息
        User user = (User)request.getSession().getAttribute("user");
        //获取部门
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        //获取下一个编码
        String number = GetFnumber.fnumbers("RK");
        //获取当前的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前时间
        String endTime = sdf.format(new Date());
        //获取前三天
        String beginTime = TimeFormat.getThreeDay();

         try{
             //获取分页
             pb = getPageBean(request,user.getFcompanyid(),beginTime,endTime);
             //获取分页数据
             List<InwareHouse> inwareHouses = pb.getBeanList();
             for (InwareHouse inwareHouse : inwareHouses) {
                 //查询子类信息
                 List<InwareHouseEntry> inwareHouseEntries = inwarehouseService.queryInwareHouseEntry(inwareHouse.getFid());
                 //放入集合
                 inwareHouse.setInwareHouseEntries(inwareHouseEntries);
             }
             //把数据传到页面
             request.setAttribute("beginTime", beginTime);
             request.setAttribute("endTime", endTime);
             request.setAttribute("inwareHouses", inwareHouses);
             request.setAttribute("type",type);
             request.setAttribute("pb", pb);
         }catch(Exception e){
             e.printStackTrace();
         }

        return "/backHome/sockingSellingandStoring/stockManagement/swareHouseChargelist";
    }

    /**
     * 跳转到操作页面(添加新的入库表)
     * @param request
     * @return
     */
    @RequestMapping("/insertInwareHouse")
    public String selecSwareHouseByFid(HttpServletRequest request,Integer type,String fid){
        //获取操作人信息
        User user = (User)request.getSession().getAttribute("user");
        //获取部门编号
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());
        //业务时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Goodstable> goodstables=goodstableService.selectGoodsAll(user.getCompanyName());
        //获取下一个编码
        String fnumber = GetFnumber.fnumbers("RK");
        //获取当前时间
        String time=sdf.format(new Date());
        type=user.getFtype();
        //传值
        request.setAttribute("type",type);
        request.setAttribute("department",department);
        request.setAttribute("time",time);
        request.setAttribute("fnumber",fnumber);
        request.setAttribute("goodstables",goodstables);
        return "/backHome/sockingSellingandStoring/stockManagement/editSwareHouseCharge";
    }
    /**
     * 添加的提交
     * @param request
     * @param inwareHouse
     * @return
     */
    @RequestMapping("/addInwareHouse")
    public String addSwareHouse(HttpServletRequest request,InwareHouse inwareHouse){
        //获取操作人信息
        User user = (User)request.getSession().getAttribute("user");
        String fnumber=request.getParameter("fnumber");
        //操作人id
        inwareHouse.setFhandlerid(user.getFid());

       //物品名称
        String []rkGoodsname=request.getParameterValues("rkGoodsname");
        //物品类型
        String []rkGoodstype=request.getParameterValues("rkGoodstype");
        //物品id
        String []rkGoodsid=request.getParameterValues("wpId");
        //物品规格id
        String []rkGgid=request.getParameterValues("rkGgid");
        //物品单价
        String []rkGoodsprice=request.getParameterValues("rkGoodsprice");
        //物品入库单价
        String []rkInwarehouseprice=request.getParameterValues("rkInwarehouseprice");
        //物品入库数量
        String []rkInwarehousequantity=request.getParameterValues("rkInwarehousequantity");
        //物品入库总价
        String []rkInwarehousetotalprices=request.getParameterValues("rkInwarehousetotalprices");
        //物品入库详情
        String[]rkInwarehouseuse=request.getParameterValues("rkInwarehousese");
        //创建时间
        String fcreatetime=request.getParameter("fbizdate");
        //获取序列号码
        String [] fesq=request.getParameterValues("fseq");


        //物品入库表添加
       inwarehouseService.addInwareHouse(inwareHouse,rkGoodsname,rkGoodsid,rkGoodstype,rkGgid,rkGoodsprice,rkInwarehouseprice,rkInwarehousequantity,rkInwarehousetotalprices,rkInwarehouseuse,fesq,user,fnumber,fcreatetime);

       return "redirect:/DrivingSys/insertInwareHouse?type=3";
        }

    /**
     *  主页面的查询
     * @param request
     * @param rkGoodsname
     * @param rkGoodstype
     * @param beginTime
     * @param endTime
     * @return
     */
    @RequestMapping("/selectInwareHouseByFid")
    public String insertSwareHouse(HttpServletRequest request,String rkGoodsname,String rkGoodstype,String beginTime,String endTime){
        PageBean<InwareHouse> pb = new PageBean<>();
        //获取操作人信息
        User user = (User)request.getSession().getAttribute("user");
        try {
            //去除空格
            rkGoodsname = rkGoodsname.trim();
            rkGoodstype = rkGoodstype.trim();
            //获取分页
            pb = getPageBean2(request,user.getFcompanyid(),rkGoodsname,rkGoodstype,beginTime,endTime);
            //获取分页数据
            List<InwareHouse> inwareHouses = pb.getBeanList();
            for (InwareHouse inwareHouse : inwareHouses) {
                //查询子类信息
                List<InwareHouseEntry> inwareHouseEntries = inwarehouseService.selectInwareHouseEntry(inwareHouse.getFid(),rkGoodsname,rkGoodstype);
                //放入集合
                inwareHouse.setInwareHouseEntries(inwareHouseEntries);
            }
            //把数据传到页面
            request.setAttribute("inwareHouses", inwareHouses);
            request.setAttribute("pb", pb);
            request.setAttribute("rkGoodsname", rkGoodsname);
            request.setAttribute("rkGoodstype", rkGoodstype);
            request.setAttribute("beginTime", beginTime);
            request.setAttribute("endTime", endTime);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "/backHome/sockingSellingandStoring/stockManagement/swareHouseChargelist";
    }
    /**
     * 进行物品的修改（修改）
     * @param request
     * @param inwareHouse
     * @param fid
     * @return
     */
    @RequestMapping("/editInwareHouse")
    public String editSwareHouse(HttpServletRequest request,InwareHouse inwareHouse,String fid){
        //获取操作人信息
        User user = (User)request.getSession().getAttribute("user");
        //获取公司id
        inwareHouse.setCfficompanyid(user.getFcompanyid());
        //获取当前时间
        String time = TimeFormat.timeFormat(new Date());
        //操作人id
        inwareHouse.setFid(fid);
        inwareHouse.setFhandlerid(user.getFid());
        //入库id
        //物品名称
        String []rkGoodsname=request.getParameterValues("rkGoodsname");
        //物品类型
        String []rkGoodstype=request.getParameterValues("rkGoodstype");
        //物品id
        String []rkGoodsid=request.getParameterValues("wpId");
        //物品规格id
        String []rkGgid=request.getParameterValues("rkGgid");
        //物品单价
        String []rkGoodsprice=request.getParameterValues("rkGoodsprice");
        //物品入库单价
        String []rkInwarehouseprice=request.getParameterValues("rkInwarehouseprice");
        //物品入库数量
        String []rkInwarehousequantity=request.getParameterValues("rkInwarehousequantity");
        //物品入库总价
        String []rkInwarehousetotalprices=request.getParameterValues("rkInwarehousetotalprices");
        //物品入库详情
        String[]rkInwarehouseuse=request.getParameterValues("rkInwarehouseuse");

        String [] fseq =request.getParameterValues("fseq");
        //物品入库表添加
         inwarehouseService.editInwareHouse(inwareHouse,rkGoodsname,rkGoodsid,rkGoodstype,rkGgid,rkGoodsprice,rkInwarehouseprice,rkInwarehousequantity,rkInwarehousetotalprices,rkInwarehouseuse,user,time,fseq);

              return "redirect:/DrivingSys/queryInwareHouseByFid?fid="+fid+"&type=4";



    }

    /**
     * 根据条件跳转到修改页面(查询)
     * @param request
     * @param fid
     * @param type
     * @return
     */
    @RequestMapping("/queryInwareHouseByFid")
    public String queryInwareHouseByinfo(HttpServletRequest request,String fid,String type){
        User user = (User)request.getSession().getAttribute("user");

        //查询父类信息
            InwareHouse inwareHouse= inwarehouseService.selectByfid(fid);
            //查询子类信息
            List<InwareHouseEntry> inwareHouseEntries =inwarehouseService.queryInwareHouseEntry(fid);
            //将子类信息放入到父类信息系里面
            inwareHouse.setInwareHouseEntries(inwareHouseEntries);
        //查询是否是经办人
        Axamine axamine = new Axamine();
        boolean state = axamine.selectAuditPerson(inwareHouse.getFnumber());

        //获取物品信息
        List<Goodstable> goodstables=goodstableService.selectGoodsAll(user.getCompanyName());
        //把数据传到页面
        request.setAttribute("AuditState", state);
        request.setAttribute("key", ActivitiKey.PUBLIC_KEY);
        request.setAttribute("type",type);
        request.setAttribute("goodstables", goodstables);
        request.setAttribute("inwareHouse", inwareHouse);
        request.setAttribute("inwareHouseEntries", inwareHouseEntries);
        return "/backHome/sockingSellingandStoring/stockManagement/editSwareHouseCharge";

    }
    /**
     * 删除
     * @param request
     * @param fid
     * @param deleteId
     * @param fnumber
     * @param fnumber2
     * @return
     */
    @RequestMapping("/deleteInwareHouseByFid")
    public String deleteInwareHouseByFid(HttpServletRequest request, String fid,String[]deleteId,String[]fnumber,String fnumber2) {

        //获取操作人信息
        User user = (User)request.getSession().getAttribute("user");
        //删除
        inwarehouseService.deleteInwareHouseByFid(fid, deleteId, fnumber, fnumber2);

        return "redirect:/DrivingSys/queryswareHouse/look.action";
    }
    /**
     * 分页
     * @param request
     * @param companyId
     * @param beginTime
     * @param endTime
     * @return
     * @throws Exception
     */
    public PageBean<InwareHouse> getPageBean(HttpServletRequest request, String companyId,
                                                String beginTime, String endTime) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        //拼接SQL语句
        StringBuffer psql = new StringBuffer();
        psql.append("select t.fid,t.fnumber,t.fdescription,t.fbizdate,u.name createName,us.name auditName,t.cfbillstate,t.FCREATETIME,t.COMPANYNAME from ");

        psql.append(" ct_ds_jxc_inwarehouse t left join t_e_user u  on t.fcreatorid = u.fid left join t_e_user us on t.fauditorid = us.fid where t.fcontrolunitid = '" + companyId + "'");

        psql.append(" and t.fbizdate between '" + beginTime + "' and '" + endTime + "'");


        psql.append(" order by t.fbizdate desc");
        int psize = 10; //每页显示数
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = inwarehouseService.selectPage(pindex, psql.toString(), psize);
        PageBean<InwareHouse> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<InwareHouse>) paramMap.get("v_cur")); //每页数据集
        return pb;
    }

    /**
     * 分页
     * @param request
     * @param companyId
     * @param rkGoodsname
     * @param rkGoodstype
     * @param beginTime
     * @param endTime
     * @return
     * @throws Exception
     */
    public PageBean<InwareHouse> getPageBean2(HttpServletRequest request,String companyId,String rkGoodsname,String rkGoodstype,String beginTime,String endTime) throws Exception
    {

        int offset;//从第几条数据开始加载
        if(request.getParameter("pager.offset")==null){
            offset=0;
        }else{
            offset=Integer.parseInt(request.getParameter("pager.offset"));
        }
        //拼接SQL语句
        StringBuffer psql = new  StringBuffer();
        psql.append("select distinct t.fid,t.fnumber,t.fdescription,t.fbizdate,u.name createName,t.COMPANYNAME,t.FFIVOUCHERED,t.FCREATETIME,");
        psql.append("t.cfbillstate from  ct_ds_jxc_inwarehouse t left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fcreatorid = us.fid ");
        psql.append("left join  ct_ds_jxc_inwarehouseentry i on i.fparentid = t.fid left join ct_ds_jxc_goodstable c on  i.RK_GOODSID = c.WP_ID  where t.fcontrolunitid = '"+companyId+"'");
        if("".equals(rkGoodsname)||rkGoodsname==null){

        }else{
            psql.append(" and i.RK_GOODSNAME = '"+rkGoodsname+"'");
        }
        if("".equals(rkGoodstype)||rkGoodstype==null){

        }else{
            psql.append(" and i.RK_GOODSTYPE = '"+rkGoodstype+"'");
        }
        if("".equals(beginTime) || "".equals(endTime)){

        }else{
            psql.append("  and  t.fbizdate between '" + beginTime + "' and '" + endTime + "'");
        }
        psql.append(" order by t.fbizdate  desc");
        int psize = 10; //每页显示数
        int pindex=offset/psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap= inwarehouseService.selectPage(pindex, psql.toString(), psize);
        PageBean<InwareHouse> pb=new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<InwareHouse>) paramMap.get("v_cur")); //每页数据集
        return pb;
    }

    /**
     * 根据条件查询物品表
     * @param name
     * @param type
     * @return
     */
    @RequestMapping("/queryRKGoodsByInfo")
    @ResponseBody
    public List<Goodstable> queryRKGoodsByInfo(String name, String type, HttpServletRequest request) {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        List<Goodstable> goodstables = new ArrayList<>();
        if("".equals(type) && "".equals(name)){

            goodstables = goodstableService.selectGoodsAll(user.getFcompanyid());
        }else{

            goodstables=goodstableService.goodsAllMassageList(name,type,"","");
        }
        return goodstables;
    }

        /**
         * 取记录总数 dmz 20160921
         * @param psql  SQL语句
         * @return Map
         * @throws Exception
         */
        public Map<String, Object> getPageBeanCount(String psql) throws Exception
        {

            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap=inwarehouseService.selectPageCount(psql);
            return paramMap;
        }

    /**
     * 提交
     * @param fid
     * @param request
     * @param fnumber
     * @param auditState
     * @return
     */
    @RequestMapping("/submitInwareHouse")
    @ResponseBody
    public int submitTrainCharge(String fid, HttpServletRequest request, String fnumber, String auditState) {
        InwareHouse inwareHouse = new InwareHouse();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //状态
        inwareHouse.setCfbillstate(4L);
        //修改人
        inwareHouse.setFlastupdateuserid(user.getFid());
        //fid
        inwareHouse.setFid(fid);
        //创建流程
        Axamine axamine = new Axamine();
        axamine.submissionProcess(fnumber);
        int i = inwarehouseService.updateInwareHouse(inwareHouse);
        //修改
        return i;
    }

    /**
     * 审核，反审核
     * @param request
     * @param type 1：审核，2：反审核
     * @param fid
     * @return
     */
    @RequestMapping("/auditInwarehouse")
    @ResponseBody
    public int auditInsuranceReg(HttpServletRequest request, String type, String fid, String message, String state, String fnumber) {
        //获取操作人信息
        User user = (User)request.getSession().getAttribute("user");
        //查询子类信息
        List<InwareHouseEntry> inwareHouseEntries = inwarehouseService.queryInwareHouseEntry(fid);

        //审核，反审核
        int i = inwarehouseService.auditInwaHouse(fid, type, user.getFid(), inwareHouseEntries, message, state,fnumber,user);
        return i;
    }

    /**
     * 导出
     * @param response
     * @param request
     * @param rkGoodsname
     * @param rkGoodstype
     * @param beginTime
     * @param endTime
     */
    @RequestMapping("/importInwareHouse")
    public void importTrainCharge(HttpServletResponse response, HttpServletRequest request,
                                  String rkGoodsname, String rkGoodstype, String beginTime, String endTime) {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //定义接收类型
        List<Object> data = new ArrayList<>();
        //查询数据
        List<InwareHouseEntry> inwareHouseEntries = inwarehouseService.selectInwareHouseByInfo(user.getFcompanyid(),rkGoodsname.trim(), rkGoodstype.trim(), beginTime, endTime);

        for (InwareHouseEntry inwareHouseEntry : inwareHouseEntries) {
            data.add(inwareHouseEntry.getFnumber());//单据编号
            data.add(inwareHouseEntry.getFbizdate2());//业务日期
            data.add(inwareHouseEntry.getShName());//审核人名称
            data.add(inwareHouseEntry.getZdrName());//制单人名称
            data.add(stateToString.billsState(inwareHouseEntry.getDjstate()));//单据状态
            data.add(inwareHouseEntry.getRkGoodstype());//类型
            data.add(inwareHouseEntry.getRkInwarehouseuse());//备注
            data.add(inwareHouseEntry.getRkGoodsname());//入库物品名称
            data.add(inwareHouseEntry.getRkInwarehousequantity());//入库物品数量
            data.add(inwareHouseEntry.getRkInwarehouseprice());//入库物品单价
            data.add(inwareHouseEntry.getRkInwarehousetotalprices());//入库总价
        }
        //头部数据
        String head[] = {"单据编号", "业务日期", "审核人名称", "制单人名称", "单据状态", "类型","备注", "入库物品名称", "入库物品数量","入库物品单价(元)", "入库总价(元)"};
        //长度
        Integer length[]={9000,4000,3000,3000,4000,4000,4000,5000,5000,5000,5000};
        try {
            //导出Excel
            CommonExport.importExcel(response, "物品入库表" + TimeFormat.getNowTime2() + ".xls", "物品入库", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
